<?php
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hyperf_mall
 * @contact  hyperf_mall@163.com
 */

namespace App\Repository;

use App\Model\GoodsCommentModel;
use App\Service\Goods\GoodsService;
use App\Utils\DB;
use Hyperf\Di\Annotation\Inject;

class GoodsCommentRepository extends BaseRepository
{
    /**
     * @Inject
     * @var GoodsCommentModel
     */
    protected $model;

    /**
     * @Inject
     * @var GoodsService
     */
    protected GoodsService $goodsService;

    /**
     * Notes: A端 商品评论列表
     * Author: Bruce.z
     * DateTime: 2022/8/19 14:37
     * @param array $condition
     * @param array $field
     * @param int $page
     * @param int $size
     * @return array
     */
    public function list(array $condition, array $field, int $page, int $size): array
    {
        $condition = array_filter($condition);
        $res =  $this->getPageRows($condition, $field, $page, $size);

        if(count($res['data'])){
            $goods_ids = array_column($res['data'],'goods_id');
            if(count($goods_ids)){
                $goods = $this->goodsService->getRows(['id'=>$goods_ids],['id','name','img']);
                $goods = array_column($goods, null, 'id');
                foreach ($res['data'] as &$re){
                    $re['purchase_time'] = isset($re['purchase_time']) ? date('Y-m-d H:i:s', $re['purchase_time']) : '';
                    $re['goods'] = $goods[$re['goods_id']] ?? [];
                    $re['image'] = $re['image']?unserialize($re['image']):'';
                }
            }
        }

        return $res;
    }

    /**
     * Notes: 获取商品评论统计
     * Author: Bruce.z
     * DateTime: 2022/9/27 15:08
     * @param int $goods_id
     * @return array
     */
    public function goodsCommentRate(int $goods_id): array
    {
        $_count= $this->_searchFactor(['goods_id'=>$goods_id,'status'=>1])
            ->select(DB::raw('count(*) as number'))
            ->groupBy('goods_mark')
            ->get()
            ->toArray();

        // 不存在时赋值
        $_count[0] = $_count[0]['number']??0;
        $_count[1] = $_count[1]['number']??0;
        $_count[2] = $_count[2]['number']??0;
        $_count[3] = array_sum($_count);
        $_count[4] = $_count[3] == 0 ? '100' : round($_count[0]*100/$_count[3], 2);

        return $_count;
    }
}
